﻿using AutoMapper;
using MediatR;
using ProduceBasicData.Api.Application.Command.RBAC.User;
using ProduceBasicData.Domain.RBAC;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Application.Handler.RBAC.User
{
    /// <summary>
    /// 删除用户命令处理器
    /// </summary>
    public class DeleteUserHandler : IRequestHandler<DeleteUserCommand, ApiResult<int>>
    {
        private readonly IBaseRespository<UserModel> _userRepository;
        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userRepository">用户仓储接口</param>
        /// <param name="mapper">对象映射器</param>
        public DeleteUserHandler(IBaseRespository<UserModel> userRepository, IMapper mapper)
        {
            _userRepository = userRepository;
            _mapper = mapper;
        }

        /// <summary>
        /// 处理删除用户命令
        /// </summary>
        /// <param name="request">删除用户命令请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>包含操作结果的ApiResult</returns>
        public async Task<ApiResult<int>> Handle(DeleteUserCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 根据ID获取用户数据
                var user = await _userRepository.GetModelAsync(request.Id);
                if (user == null)
                {
                    // 用户不存在时返回错误信息
                    return new ApiResult<int>
                    {
                        Msg = "用户不存在",
                        Code = ApiEnum.Failed
                    };
                }

                // 执行软删除（标记Isdel为true）
                user.Isdel = true;
                await _userRepository.Update(user);

                // 返回成功结果
                return new ApiResult<int>
                {
                    Code = ApiEnum.Success,
                    Msg = "删除成功",
                    Data = user.Id
                };
            }
            catch (Exception ex)
            {
                // 异常时返回错误信息
                return new ApiResult<int>
                {
                    Code = ApiEnum.Failed,
                    Msg = $"删除用户时发生错误: {ex.Message}"
                };
            }
        }
    }
}
